#include <time.h>
#include "../../ui.h"
#include "../../ui_helpers.h"
#include "../Inc/ui_HomePage.h"
#include "../Inc/ui_MenuPage.h"
#include "../Inc/ui_HRPage.h"
#include "../Inc/ui_SetPage.h"

#include "../../../Func/Inc/HWDataAccess.h"
#include "SDL_image.h"


///////////////////// VARIABLES ////////////////////
//home page
static lv_obj_t *obj_timeshow = NULL;
static lv_obj_t *obj_top_status = NULL;
static lv_obj_t *obj_batshow = NULL;
static lv_obj_t *obj_diskusbshow = NULL;
static lv_obj_t *obj_diskforbidshow = NULL;
static lv_obj_t *obj_zoomshow = NULL;
static lv_obj_t *obj_zoom_labelshow = NULL;

static lv_img_dsc_t *img_batshow[XT_BAT_STATUS_MAX] = {NULL,};
static lv_img_dsc_t *img_diskshow[XT_SD_STATUS_MAX] = {NULL,};
static lv_img_dsc_t *img_zoomshow[XT_ZOOM_STATUS_MAX] = {NULL,};

lv_obj_t * ui_HomePage;
lv_obj_t * ui_TimeHourLabel;
lv_obj_t * ui_TimeColonLabel;
lv_obj_t * ui_TimeMinuteLabel;
lv_obj_t * ui_BatArc;
lv_obj_t * ui_BaticonLabel;
lv_obj_t * ui_BatNumLabel;
//drop down
//power slider
lv_obj_t * ui_PowerPage;
lv_obj_t * ui_PowerSlider;
lv_obj_t * ui_PowerDownLabel;

lv_timer_t * ui_HomePageTimer;

// variables
uint8_t ui_TimeHourValue = 11;
uint8_t ui_TimeMinuteValue = 59;
uint8_t ui_DateMonthValue = 11;
uint8_t ui_DateDayValue = 8;
uint8_t ui_DataWeekdayValue = 2;

uint8_t ui_BatArcValue = 70;
///////////////////// Page Manager //////////////////
Page_t Page_Home = {ui_HomePage_screen_init, ui_HomePage_screen_deinit, &ui_HomePage};
Page_t Page_Power = {ui_PowerPage_screen_init, ui_PowerPage_screen_deinit, &ui_PowerPage};

void ui_homepage_draw(int zoom);

/////////////////// private timer ///////////////////
// need to be destroyed when the page is destroyed
static void HomePage_timer_cb(lv_timer_t * timer) {
    if(obj_timeshow) {
        ui_timeshow_update(0, obj_timeshow);
    }
}


///////////////////// FUNCTIONS ////////////////////
void ui_event_HomePage(lv_event_t * e) {
    lv_event_code_t event_code = lv_event_get_code(e);
    lv_obj_t * target = lv_event_get_target(e);
    xt_prt("event_code:%d:%x-%d\n", event_code, event_code, lv_event_get_key(e));
    if(event_code == LV_EVENT_GESTURE) {
        int dir = lv_indev_get_gesture_dir(lv_indev_get_act());
        xt_prt("dir:%d:%x\n", dir, dir);
        if(dir == LV_DIR_RIGHT) {
            Page_Load(&Page_Menu);
        }
        else if(dir == LV_DIR_RU) {
            ui_homepage_draw(2);
        }
        else if(dir == LV_DIR_LB) {
            ui_homepage_draw(1);
        }
    }
    else if(event_code == LV_EVENT_KEY) {
        if(XtKeyPad2HomePMapping(lv_event_get_key(e)) == XT_KEY_EVENT_ENTER) {
            Page_Load(&Page_Menu);
        }
    }
}

void ui_event_PowerButton(lv_event_t * e) {
    lv_event_code_t event_code = lv_event_get_code(e);
//    xt_prt("event_code:%d:%x\n", event_code, event_code);
    lv_obj_t * target = lv_event_get_target(e);
    if((event_code == LV_EVENT_CLICKED) ||
        ((event_code == LV_EVENT_KEY) && (XtKeyPad2HomePMapping(lv_event_get_key(e)) == XT_KEY_EVENT_ENTER))) {
            //power slider
      Page_Load(&Page_Power);
            // ui_PowerPage_screen_init();
            // lv_scr_load_anim(ui_PowerPage,LV_SCR_LOAD_ANIM_MOVE_RIGHT,0,0,true);
            // user_Stack_Push(&ScrRenewStack,(long long int)&ui_PowerPage);
    }
}

///////////////////// SCREEN init ////////////////////
void ui_homepage_draw(int zoom) {
    static int cur_zoom = 0;
    if(cur_zoom == zoom) return;
    if(zoom == 2) {
        xt_prt("dir:%d:%x\n", zoom, zoom);
        lv_obj_set_width(ui_TimeHourLabel, LV_SIZE_CONTENT);   /// 10
        lv_obj_set_height(ui_TimeHourLabel, LV_SIZE_CONTENT);    /// 10
        lv_obj_set_style_text_font(ui_TimeHourLabel, &ui_font_Cuyuan48, LV_PART_MAIN | LV_STATE_DEFAULT);
        lv_obj_set_width(ui_BatArc, 50);
        lv_obj_set_height(ui_BatArc, 50);
    }
    else if(zoom == 1) {
        xt_prt("dir:%d:%x\n", zoom, zoom);
        lv_obj_set_width(ui_TimeHourLabel, LV_SIZE_CONTENT);   /// 10
        lv_obj_set_height(ui_TimeHourLabel, LV_SIZE_CONTENT);    /// 10
        lv_obj_set_style_text_font(ui_TimeHourLabel, &ui_font_Cuyuan30, LV_PART_MAIN | LV_STATE_DEFAULT);
        lv_obj_set_width(ui_BatArc, 25);
        lv_obj_set_height(ui_BatArc, 25);
    }
    cur_zoom = zoom;
}

void ui_obj_rect_bg(lv_obj_t *obj, lv_color_t bg_color, int width, int height, int pos_x, int pos_y) {
    lv_obj_set_size(obj, width, height);
    lv_obj_clear_flag(obj, LV_OBJ_FLAG_SCROLLABLE);             //关闭自动滚动条功能
    lv_obj_set_style_pad_all(obj, 0, _LV_STYLE_STATE_CMP_SAME); //控件间距为0
    lv_obj_set_style_radius(obj, 0,0);// 设置样式的圆角弧度
    lv_obj_set_style_border_width(obj,0,0);// 设置边框宽度
    lv_obj_set_style_bg_color(obj, bg_color, 0);
    lv_obj_set_pos(obj, pos_x, pos_y);
}

void ui_timeshow_update(int flag_rtc, lv_obj_t *obj) {
    static int t_flag_rtc = 0, t_flag_min = 0;
    int hour = 0;
    char tempStr[16];
    char str_time[32];
    char formatStr[6];
    time_t timep;
    struct tm *p;
    time(&timep);
    p = gmtime(&timep);
    int time_format = 0;
    int date_format = 0;
//    time_format = get_ini_intVal(INI_TIME_FORMAT);
//    date_format = get_ini_intVal(INI_DATE_FORMAT);
    if (time_format) {
        if (p->tm_hour > 12) {
            hour = p->tm_hour - 12;
            sprintf(formatStr, "%s ", "PM");
        }
        else {
            if(p->tm_hour == 0) {
                hour = 12;
                sprintf(formatStr, "%s ", "AM");
            }
            else if(p->tm_hour == 12)
            {
                hour = 12;
                sprintf(formatStr, "%s ", "PM");
            }
            else
            {
                hour = p->tm_hour;
                sprintf(formatStr, "%s ", "AM");
            }
        }
        sprintf(tempStr, "%s %02d", formatStr, hour);
        if (date_format == 0) {
            sprintf(str_time, "%4d/%02d/%02d \n%s : %02d",
                1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday, tempStr, p->tm_min);
        }
        else if (date_format == 1) { //日/日/年
            sprintf(str_time, "%02d/%02d/%4d \n%s : %02d",
                p->tm_mday, 1 + p->tm_mon, 1900 + p->tm_year, tempStr, p->tm_min);
        }
        else { //月/日/年
            sprintf(str_time, "%02d/%02d/%4d \n%s : %02d",
                1 + p->tm_mon, p->tm_mday, 1900 + p->tm_year, tempStr, p->tm_min);
        }
    }
    else {
        if (date_format == 0) { //年/月/日
            sprintf(str_time, "%4d/%02d/%02d \n%02d : %02d",
                1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min);
        }
        else if (date_format == 1) { //日/日/年
            sprintf(str_time, "%02d/%02d/%4d \n%02d : %02d",
                p->tm_mday, 1 + p->tm_mon, 1900 + p->tm_year, p->tm_hour, p->tm_min);
        }
        else { //月/日/年
            sprintf(str_time, "%02d/%02d/%4d \n%02d : %02d",
                1 + p->tm_mon, p->tm_mday, 1900 + p->tm_year, p->tm_hour, p->tm_min);
        }
    }
    /*一分钟更新一次*/
    if ((t_flag_min != p->tm_min) || (t_flag_min != flag_rtc)) {
        t_flag_min = p->tm_min;
        lv_label_set_text(obj, str_time);
        t_flag_min = flag_rtc;
    }
}
static bool png_init_state=false;
static bool jpg_init_state=false;

lv_img_dsc_t *load_image_resource(char *res_path)
{
    lv_img_dsc_t *img_res = NULL;
    static bool flag_init = false;
    if (!flag_init) {
        flag_init = IMG_Init(IMG_INIT_PNG);
    }

    // 加载背景图
    SDL_Surface *image_surface = IMG_Load(res_path);
    if (NULL == image_surface) {
        // IMG_Quit();
        flag_init = false;
        return NULL;
    }
    img_res = malloc(sizeof(lv_img_dsc_t));
    memset(img_res, 0, sizeof(lv_img_dsc_t));
    int i, j;
    img_res->header.always_zero = 0;
    img_res->header.w = image_surface->w;
    img_res->header.h = image_surface->h;
    img_res->data_size = image_surface->w * image_surface->h * LV_IMG_PX_SIZE_ALPHA_BYTE;
    img_res->header.cf = LV_IMG_CF_TRUE_COLOR_ALPHA;
    img_res->data = malloc(img_res->data_size);
    char *row_data = (char *)image_surface->pixels;
    char *temp_data = (char *)img_res->data;
    // memcpy(row_data, image_surface->pixels, img_res->data_size);
    for (i = 0; i < img_res->data_size; i = i + 4)
    {
        temp_data[i + 0] = row_data[i + 2];
        temp_data[i + 1] = row_data[i + 1];
        temp_data[i + 2] = row_data[i + 0];
        temp_data[i + 3] = row_data[i + 3];
    }
    SDL_FreeSurface(image_surface);
    return img_res;
}

void release_resource(lv_img_dsc_t **res) {
    if (*res) {
        if ((*res)->data) {
            free((void *)(*res)->data);
        }
        free((void *)(*res));
        *res = NULL;
    }
}

void ui_load_battery_icon_resource(void) {
    img_batshow[XT_BAT_STATUS_4] = load_image_resource(UI_RESOURCE_PATH"battery_4.png");
    img_batshow[XT_BAT_STATUS_3] = load_image_resource(UI_RESOURCE_PATH"battery_3.png");
    img_batshow[XT_BAT_STATUS_2] = load_image_resource(UI_RESOURCE_PATH"battery_2.png");
    img_batshow[XT_BAT_STATUS_1] = load_image_resource(UI_RESOURCE_PATH"battery_1.png");
    img_batshow[XT_BAT_STATUS_0] = load_image_resource(UI_RESOURCE_PATH"battery_0.png");
    img_batshow[XT_BAT_STATUS_EMPTY] = load_image_resource(UI_RESOURCE_PATH"battery_empty.png");
    img_batshow[XT_BAT_STATUS_CHARGE] = load_image_resource(UI_RESOURCE_PATH"battery_charge.png");
    img_batshow[XT_BAT_STATUS_LOADING] = load_image_resource(UI_RESOURCE_PATH"battery_loading.png");
    for(int i_cnt  = 0; i_cnt < XT_BAT_STATUS_MAX; i_cnt++) {
        if(img_batshow[i_cnt] == NULL) {
            xt_prt("%d not init, check\n", i_cnt);
        }
    }
}

void ui_unload_battery_icon_resource(void) {
    for(int i_cnt  = 0; i_cnt < XT_BAT_STATUS_MAX; i_cnt++) {
        if(img_batshow[i_cnt] != NULL) {
            release_resource(&(img_batshow[i_cnt]));
        }
    }
}

void ui_load_disk_icon_resource(void) {
    img_diskshow[XT_SD_STATUS_DISKUSB] = load_image_resource(UI_RESOURCE_PATH"index_icon_usb.png");
    img_diskshow[XT_SD_STATUS_DISKFORBID] = load_image_resource(UI_RESOURCE_PATH"index_icon_sd.png");
    for(int i_cnt  = 0; i_cnt < XT_SD_STATUS_MAX; i_cnt++) {
        if(img_diskshow[i_cnt] == NULL) {
            xt_prt("%d not init, check\n", i_cnt);
        }
    }
}

void ui_unload_disk_icon_resource(void) {
    for(int i_cnt  = 0; i_cnt < XT_SD_STATUS_MAX; i_cnt++) {
        if(img_diskshow[i_cnt] != NULL) {
            release_resource(&(img_diskshow[i_cnt]));
        }
    }
}

void ui_load_zoom_icon_resource(void) {
    img_zoomshow[XT_ZOOM_STATUS_BASE] = load_image_resource(UI_RESOURCE_PATH"icon_zoom_null.png");
    for(int i_cnt  = 0; i_cnt < XT_ZOOM_STATUS_MAX; i_cnt++) {
        if(img_zoomshow[i_cnt] == NULL) {
            xt_prt("%d not init, check\n", i_cnt);
        }
    }
}

void ui_unload_zoom_icon_resource(void) {
    for(int i_cnt  = 0; i_cnt < XT_ZOOM_STATUS_MAX; i_cnt++) {
        if(img_zoomshow[i_cnt] != NULL) {
            release_resource(&(img_zoomshow[i_cnt]));
        }
    }
}
void ui_set_lvgl_image_color(lv_obj_t *obj,lv_color_t color) {
    if(obj != NULL){
        lv_obj_set_style_img_recolor(obj, color, 0);  // 重新着色透明度
        lv_obj_set_style_img_recolor_opa(obj, LV_OPA_100, 0); // 重新着色颜色
    }
}


void ui_load_icon_resource(void) {
    ui_load_battery_icon_resource();
    ui_load_disk_icon_resource();
    ui_load_zoom_icon_resource();
}

void ui_HomePage_screen_init(void) {
    ui_MenuScrollY = 0;
    uint8_t value_strbuf[10];
    lv_color_t bg_color, text_color;
    bg_color.full = COLOR_BLACK; text_color.full = COLOR_WHITE;
    //time
    //bat
    //tf
    //usb
    ui_load_icon_resource();
//    ui_HomePage = lv_obj_create(lv_scr_act());
    ui_HomePage = lv_obj_create(NULL);
    lv_obj_clear_flag(ui_HomePage, LV_OBJ_FLAG_SCROLLABLE);      /// Flags
    groupRect = lv_group_create();
    lv_indev_set_group(indev_keypad, groupRect);
    lv_group_add_obj(groupRect, ui_HomePage);
    
    obj_top_status = lv_obj_create(ui_HomePage);
    ui_obj_rect_bg(obj_top_status, bg_color, LV_HOR_RES, LV_VER_RES, 0, 0);

    obj_timeshow = lv_label_create(obj_top_status);
    lv_obj_align(obj_timeshow, LV_ALIGN_TOP_LEFT, 0, 0);
    lv_obj_set_style_text_font(obj_timeshow, ttf_info_24.font, 0);
    lv_obj_set_style_text_color(obj_timeshow, text_color, 0);
    lv_obj_set_style_bg_opa(obj_timeshow, LV_OPA_100, 0); // 设置透明度
    lv_obj_set_style_bg_color(obj_timeshow, bg_color, 0);

    obj_batshow = lv_img_create(obj_top_status); int x_offset = 0;
    lv_obj_align(obj_batshow, LV_ALIGN_TOP_RIGHT, x_offset, 0);
    lv_img_set_src(obj_batshow, img_batshow[XT_BAT_STATUS_CHARGE]);
    x_offset += 70;

    obj_zoomshow = lv_img_create(obj_top_status);
    lv_obj_align(obj_zoomshow, LV_ALIGN_TOP_RIGHT, -x_offset, 0);
    lv_img_set_src(obj_zoomshow, img_zoomshow[XT_ZOOM_STATUS_BASE]);
    ui_set_lvgl_image_color(obj_zoomshow, text_color);
    lv_img_set_zoom(obj_zoomshow, (128*6)/4);
    obj_zoom_labelshow = lv_label_create(obj_zoomshow);
    lv_obj_align(obj_zoom_labelshow, LV_ALIGN_LEFT_MID, 12, 0);
    lv_obj_set_style_text_font(obj_zoom_labelshow, ttf_info_16.font, 0);
    lv_obj_set_style_text_color(obj_zoom_labelshow, text_color, 0);
    lv_label_set_text(obj_zoom_labelshow, "1X");
    ui_set_lvgl_image_color(obj_zoom_labelshow, text_color);
    x_offset += 40;

    obj_diskusbshow = lv_img_create(obj_top_status);
    lv_obj_align(obj_diskusbshow, LV_ALIGN_TOP_RIGHT, -x_offset, 0);
    lv_img_set_src(obj_diskusbshow, img_diskshow[XT_SD_STATUS_DISKUSB]);
    ui_set_lvgl_image_color(obj_diskusbshow, text_color);
    lv_img_set_zoom(obj_diskusbshow, (128*14)/8);
    x_offset += 40;

    obj_diskforbidshow = lv_img_create(obj_top_status);
    lv_obj_align(obj_diskforbidshow, LV_ALIGN_TOP_RIGHT, -x_offset, 0);
    lv_img_set_src(obj_diskforbidshow, img_diskshow[XT_SD_STATUS_DISKFORBID]);
    ui_set_lvgl_image_color(obj_diskforbidshow, text_color);
    lv_img_set_zoom(obj_diskforbidshow, (128*6)/4);

    //events
    lv_obj_add_event_cb(ui_HomePage, ui_event_HomePage, LV_EVENT_ALL, NULL);

    //timer
    ui_HomePageTimer = lv_timer_create(HomePage_timer_cb, 500,  NULL);

}


void ui_PowerPage_screen_init(void) {
    ui_PowerPage = lv_obj_create(NULL);
    lv_obj_clear_flag(ui_PowerPage, LV_OBJ_FLAG_SCROLLABLE);      /// Flags
    lv_group_t *group = lv_group_create();
    lv_indev_set_group(indev_keypad, group);
    lv_group_add_obj(group, ui_PowerPage);

    //events
    lv_obj_add_event_cb(ui_PowerPage, ui_event_BackPage, LV_EVENT_ALL, NULL);

}

/////////////////// SCREEN deinit ////////////////////
void ui_HomePage_screen_deinit(void) {
  lv_timer_del(ui_HomePageTimer);
}

void ui_PowerPage_screen_deinit(void) {}
